package top.scsoul.voes.framework.filter;

import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.scsoul.voes.framework.config.SpringSecurityConfig;
import top.scsoul.voes.framework.web.service.TokenService;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class AuthFilter extends OncePerRequestFilter {
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    @Autowired
    SpringSecurityConfig springSecurityConfig;

    @Autowired
    TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(header);
        UsernamePasswordAuthenticationToken authentication = null;
        try {
            if (token != null) {
                //验证token,开始认证
                String username = tokenService.getUsername(token);
                UserDetails userDetails = springSecurityConfig.loadUserByUsername(username);
                authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            }
        } catch (ExpiredJwtException e) {
            log.error("token过期");




        } finally {
            //开始授权
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request, response);
        }
    }
}
